import path from 'node:path'
import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import vitePluginUniRouter from './src/plugins/uni-simple-router/compiler'
import autoImport from 'unplugin-auto-import/vite'
import { uniuseAutoImports } from '@uni-helper/uni-use'
import UniPlatformModifier from '@uni-helper/vite-plugin-uni-platform-modifier'
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'

// https://vitejs.dev/config/
export default defineConfig(async ({ mode }) => {
  const env = loadEnv(mode, process.cwd())

  const viteEnvKeys = Object.keys(env).filter(key => key.startsWith('VITE_'))

  const define = {
    ...viteEnvKeys.reduce((config, variable) => {
      config[`process.env.${variable}`] = JSON.stringify(env[variable])
      return config
    }, {}),
  }

  const UnoCSS = (await import('unocss/vite')).default

  return {
    plugins: [
      vitePluginUniRouter({
        pluginPath: `./plugins/uni-simple-router`,
      }),
      uni(),
      autoImport({
        imports: [
          uniuseAutoImports(),
        ],
        // 可以选择auto-import.d.ts生成的位置，使用ts建议设置为'src/auto-import.d.ts'
        // dts: 'src/auto-import.d.ts'
        // 自动生成'eslintrc-auto-import.json'文件，在'.eslintrc.cjs'的'extends'中引入解决报错
        eslintrc: {
          enabled: true,
        },
      }),
      UnoCSS(),
      UniPlatformModifier(),
      // #ifndef MP
      mockDevServerPlugin({
        // prefix: '^/mock/',
        prefix: ['^/mock', '/mock/'],
        // wsPrefix: [],
        include: ['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}'],
        // 配置读取 mock文件时，需要排除的文件
        exclude: [
          '**/node_modules/**',
          '**/.vscode/**',
          '**/.git/**',
          '**/.history/**',
          '**/.hbuilderx/**',
          '**/demo/**',
          '**/dist/**',
        ],
        log: 'info', // 开启接口日志打印，或 配置日志级别。类型：boolean | 'debug' | 'info' | 'warn' | 'error' | 'silent'
        reload: false, // mock资源热更新时，仅更新了数据内容，但是默认不重新刷新页面。
        // cors: true, // 开启 CORS 或 配置 CORS 选项。 通常你不需要配置它，默认从 vite server.cors 继承配置。
        // formidableOptions: undefined,
        // cookiesOptions: undefined,
        // bodyParserOptions: undefined,
        // priority: undefined
      }),
      // #endif
    ],
    base: env.VITE_USER_NODE_ENV === 'production' ? './' : '/',
    resolve: {
      alias: {
        '^@': path.resolve(__dirname, './src/'),
        'simpleRouter': path.resolve(__dirname, './src/plugins/uni-simple-router/'),
        'images': path.resolve(__dirname, './src/static/images/'),
        'i18n': path.resolve(__dirname, './src/plugins/i18n/'),
        'api': path.resolve(__dirname, './src/api/'),
        'config': path.resolve(__dirname, './src/config.js'),
      },
    },
    optimizeDeps: {
      exclude: ['vue-demi'],
    },
    build: {
      target: 'es6',
      cssTarget: 'chrome61', // https://cn.vitejs.dev/config/build-options.html#build-csstarget
      // sourcemap: false, // 不生成 source map
      terserOptions: {
        compress: { // 打包时清除 console 和 debug 相关代码
          drop_console: true,
          drop_debugger: true,
        },
      },
      //指定输出路径
      // outDir: "web",
      //生成静态资源的存放路径
      // assetsDir: "assets",
      //默认情况下，若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录。
      // emptyOutDir: true,
      //terser 构建后文件体积更小
      minify: "terser",
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/variables.scss";',
          javascriptEnabled: true,
        },
      },
    },
    server: {
      host: 'localhost',
      port: '8080',
      open: true,
      proxy: {
        '/vite-uniapp-template': {
          target: 'https://api.virapi.com/vir_gitee2ca8413ea4909',
          changeOrigin: true,
          ws: true, // 支持 websocket
          // rewrite: (path) => path.replace(/^\/api/, '') // 路径重写
          // rewrite: path =>
          //   path.replace(new RegExp(`^api`), ''),
          rewrite: path =>
            path.replace(/^vite-uniapp-template/, ''),
        },
        '^/mock': {
          target: env.VITE_APP_API_URL,
          changeOrigin: true,
          rewrite: path =>
            path.replace(/^mock/, ''),
        }
      },
    },
    define
  }
})
